package com.abocode.aichat.core.application;
import com.abocode.aichat.core.domain.entity.Message;
import com.abocode.aichat.core.domain.repository.MessageRepository;
import com.abocode.aichat.core.domain.repository.RedisMessageService;
import com.abocode.aichat.core.interfaces.constant.ApplicationCostant;
import com.abocode.aichat.server.exception.EntityFormatException;
import com.abocode.aichat.server.pipeline.MessagePipeline;
import com.abocode.aichat.utils.HappBeanUtils;
import com.abocode.aichat.utils.SecurityDesUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.Map;

/**
 * Created by guanxf on 2015/8/6.
 */
@Service
public class MessageSentService  implements MessagePipeline {
    @Autowired
    private MessageRepository messageRepository;
    @Autowired
    private RedisMessageService redisMessageService;

    @Override
    public void messageStore(Object obj) {
        Map body= (Map) obj;
        Message  message= (Message) HappBeanUtils.mapToObject(body,Message.class);
        try {
            String to = SecurityDesUtils.decrypt(message.getTo(), ApplicationCostant.JID_ENCRYPT_KEY);
            message.setTo(to);
        } catch (Exception e) {
            throw new EntityFormatException("Jid decrypt is failure ");
        }
        message.setCreateTime(new Date());//DateUtils.getCurrentDate(DateUtils.FORMAT_FOR_yyyy_MM_dd_HH_mm_ss)
        String  device="all";
        if(StringUtils.isEmpty(message.getDevice())){
            message.setDevice(device);
        }
        redisMessageService.save(message);
        messageRepository.save(message);
    }

    //获取离线消息
    public Object readMessage(final String msgKey) {
       return   redisMessageService.readMessage(msgKey);
    }
}
